// Json格式转换API在这个包里面
import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:puppy_store/main.dart';
import 'package:puppy_store/pages/account/register_mobile_page.dart';
import 'package:puppy_store/service/account_api.dart';
import 'package:puppy_store/utils/common_utils.dart';
import 'package:shared_preferences/shared_preferences.dart';

class AccountLoginPage extends StatefulWidget {
  const AccountLoginPage({super.key});

  @override
  State<AccountLoginPage> createState() => _AccountLoginPageState();
}

class _AccountLoginPageState extends State<AccountLoginPage> {
  // 是否展示一键清空的安妮
  bool _showClearAccount = false;
  // 账号输入框控制器
  late TextEditingController _accountController;
  // 账号输入框焦点
  late FocusNode _accountFocusNode;

  /// 监听账号输入框文本变化
  void _accountOnChange(String? accountText) {
    if (accountText != null && accountText.isNotEmpty) {
      setState(() {
        _showClearAccount = true;
      });
    } else {
      setState(() {
        _showClearAccount = false;
      });
    }
  }

  // 清除账号框内容
  void _clearAccount() {
    _accountController.clear();
    setState(() {
      _showClearAccount = false;
    });
  }

  // 是否展示一键清空的安妮
  bool _showClearPassword = false;
  // 密码输入框控制器
  late TextEditingController _passwordController;
  // 密码框焦点
  late FocusNode _passwordFocusNode;
  // 是否明文显示密码
  bool _isObscureText = true;

  /// 是否同意协议
  bool _isAgree = true;

  /// 监听密码输入框文本变化
  void _passwordOnChange(String? passwordText) {
    if (passwordText != null && passwordText.isNotEmpty) {
      setState(() {
        _showClearPassword = true;
      });
    } else {
      setState(() {
        _showClearPassword = false;
      });
    }
  }

  // 清除密码框内容
  void _clearPassword() {
    _passwordController.clear();
    setState(() {
      _showClearPassword = false;
    });
  }

  // 登录按钮点击事件
  void _loginButtonOnTap() async {
    _accountFocusNode.unfocus();
    _passwordFocusNode.unfocus();

    // 账号和密码都有信息时才校验
    if (_accountController.text.isEmpty || _passwordController.text.isEmpty) {
      // 账号或密码为空时, 提示用户
      EasyLoading.showToast("账号或密码为空");
      return;
      // debugPrint("账号或密码为空");
    }
    // 校验账号格式：5-20位的数字和字母组合
    RegExp accountRegExp = RegExp(r'^[0-9a-zA-Z]{5,20}$');
    bool isMatchAccount = accountRegExp.hasMatch(_accountController.text);
    if (!isMatchAccount) {
      // 账号格式不正确时, 提示用户
      EasyLoading.showToast("账号格式不正确");
      // debugPrint("账号格式不正确");
      return;
    }
    // 校验密码格式：6-20位的数字和字母组合
    RegExp passwordRegExp = RegExp(r'^[0-9a-zA-Z]{6,20}$');
    bool isMatchPassword = passwordRegExp.hasMatch(_passwordController.text);
    if (!isMatchPassword) {
      // 密码格式不正确时, 提示用户
      EasyLoading.showToast("密码格式不正确");
      // debugPrint("密码格式不正确");
      return;
    }

    // 校验是否同意用户协议：必须同意用户协议
    if (!_isAgree) {
      // 必须同意用户协议时, 提示用户
      EasyLoading.showToast("必须同意用户协议");
      // debugPrint("必须同意用户协议");
      return;
    }

    // 发送登录请求 测试账号：13123456789 密码：123456
    try {
      Map userInfo = await AccountApi.login(
        // _accountController.text,
        "13123456789",
        _passwordController.text,
      );

      // 本地缓存用户信息
      // 获取SharePreferences实例
      bool ret = await saveUserInfo(userInfo);

      // 测试获取用户信息
      // Map? userInfo2 = await getUserInfo();
      // debugPrint("登录成功, 用户信息: ${userInfo2.toString()}");

      // 发送登录成功事件
      eventBus.fire(LoginSuccessEvent());

      EasyLoading.showToast("登录成功");
      // 登录成功后, 跳转到首页
      Navigator.pop(context);
    } on DioException catch (e) {
      // 明确制定的异常
      EasyLoading.showToast("登录失败: ${e.response?.data['message']}");
    }
  }

  @override
  void initState() {
    _accountController = TextEditingController(text: '');
    _passwordController = TextEditingController(text: '');
    _accountFocusNode = FocusNode();
    _passwordFocusNode = FocusNode();

    // 监听密码输入框焦点变化
    _passwordFocusNode.addListener(() {
      // debugPrint("密码输入框焦点变化: ${_passwordFocusNode.hasFocus}");
      setState(() {});
    });

    super.initState();
  }

  @override
  void dispose() {
    _accountController.dispose();
    _passwordController.dispose();
    _accountFocusNode.dispose();
    _passwordFocusNode.dispose();
    super.dispose();
  }

  /// 构建密码输入框
  Widget _buildPasswordTextField() {
    return Container(
      height: 82.0,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Row(
            children: [
              Text(
                "密码",
                style: TextStyle(fontSize: 14.0, color: Color(0xFF333333)),
              ),
              // 这里必须限定TextField的范围，不然会报布局的异常
              Expanded(
                child: Padding(
                  padding: EdgeInsets.only(left: 10.0),
                  child: Container(
                    height: 34.0,
                    child: TextField(
                      controller: _passwordController,
                      // 焦点,用于点击空白处隐藏键盘
                      focusNode: _passwordFocusNode,
                      // 密码方式
                      obscureText: _isObscureText,
                      onChanged: (String? text) {
                        _passwordOnChange(text);
                      },
                      cursorRadius: Radius.circular(10.0),
                      cursorColor: Color(0xFFFFBD3B),
                      cursorHeight: 18.0,
                      style: TextStyle(
                        fontSize: 14.0,
                        color: Color(0xFF333333),
                      ),
                      decoration: InputDecoration(
                        contentPadding: EdgeInsets.only(top: 8.0),
                        isCollapsed: true,
                        border: InputBorder.none,
                        hintText: '6到20位字母、数字和符号组合',
                        hintStyle: TextStyle(
                          fontSize: 13.0,
                          color: Color(0xffD8D8D8),
                        ),
                      ),
                      keyboardType: TextInputType.text,
                      textInputAction: TextInputAction.done,
                    ),
                  ),
                ),
              ),

              // 一键清除
              _showClearPassword
                  ? GestureDetector(
                    onTap: () {
                      _clearPassword();
                    },
                    child:
                    // 一键清除
                    Image.asset('assets/text_clean.png'),
                  )
                  : Container(),

              // 是否明文显示密码
              Padding(
                padding: EdgeInsets.only(left: 20.0),
                child: GestureDetector(
                  onTap: () {
                    setState(() {
                      _isObscureText = _isObscureText;
                    });
                  },
                  child:
                      _isObscureText
                          ? Image.asset(
                            'assets/yanjing.png',
                            gaplessPlayback: true,
                          )
                          : Image.asset(
                            'assets/yanjing_on.png',
                            gaplessPlayback: true,
                          ),
                ),
              ),
            ],
          ),
          // 分割线
          Padding(
            padding: EdgeInsets.only(top: 14.0),
            child: Container(
              height: 1.0,
              decoration: BoxDecoration(color: Color(0xFFE4E4E4)),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建账号输入框
  Widget _buildAccountTextField() {
    return Container(
      height: 82.0,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          Row(
            children: [
              Text(
                "账号",
                style: TextStyle(fontSize: 14.0, color: Color(0xFF333333)),
              ),
              // 这里必须限定TextField的范围，不然会报布局的异常
              Expanded(
                child: Padding(
                  padding: EdgeInsets.only(left: 10.0),
                  child: Container(
                    height: 34.0,
                    child: TextField(
                      // 光标的设置
                      controller: _accountController,
                      // 焦点,用于点击空白处隐藏键盘
                      focusNode: _accountFocusNode,
                      cursorRadius: Radius.circular(10.0),
                      cursorColor: Color(0xFFFFBD3B),
                      cursorHeight: 18.0,
                      onChanged: (String? text) {
                        _accountOnChange(text);
                      },
                      style: TextStyle(
                        fontSize: 14.0,
                        color: Color(0xFF333333),
                      ),
                      // 输入文本的样式
                      decoration: InputDecoration(
                        // TextField文本居中
                        contentPadding: EdgeInsets.only(top: 8.0),
                        // 辅助文本居中
                        isCollapsed: true,
                        // 去除边框
                        border: InputBorder.none,
                        // 占位提示文字和样式
                        hintText: '请输入用户名或手机号',
                        hintStyle: TextStyle(
                          fontSize: 13.0,
                          color: Color(0xffD8D8D8),
                        ),
                      ),
                      // 键盘的设置
                      keyboardType: TextInputType.text, // 键盘类型
                      textInputAction: TextInputAction.done, // 控制键盘的enter键
                    ),
                  ),
                ),
              ),

              _showClearAccount
                  ? GestureDetector(
                    onTap: () {
                      _clearAccount();
                    },
                    child:
                    // 一键清除
                    Image.asset('assets/text_clean.png'),
                  )
                  : Container(),
            ],
          ),
          // 分割线
          Padding(
            padding: EdgeInsets.only(top: 14.0),
            child: Container(
              height: 1.0,
              decoration: BoxDecoration(color: Color(0xFFE4E4E4)),
            ),
          ),
        ],
      ),
    );
  }

  /// 绿色背景 + 账号密码输入框 + 小兔子
  Widget _buildLoginCard() {
    // 定位的父组件
    return Container(
      height: 316.0, // 绿色背景高度+账号密码输入框高度-重合的高度20.0
      child: Stack(
        alignment: Alignment.topCenter,
        children: [
          // 绿色背景
          Container(height: 132.0, color: Color(0xFF00BF9B)),
          // 账号密码输入框
          Positioned(
            top: 110.0,
            left: 20.0,
            right: 20.0,
            child: Container(
              height: 204.0,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(10.0),
              ),
              padding: EdgeInsets.only(
                left: 20.0,
                top: 10.0,
                right: 20.0,
                bottom: 30.0,
              ),
              // 账号和密码
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  // 用户名
                  _buildAccountTextField(),
                  // 密码
                  _buildPasswordTextField(),
                ],
              ),
            ),
          ),
          // 小兔子
          Positioned(
            top: 0.0,
            child:
                _passwordFocusNode.hasFocus
                    ? Image.asset(
                      'assets/close_eyes_half.png',
                      gaplessPlayback: true, // 防止图片闪烁, 无缝播放
                    )
                    : Image.asset(
                      'assets/open_eyes.png',
                      gaplessPlayback: true,
                    ),
          ),
        ],
      ),
    );
  }

  /// 用户协议
  Widget _buildAgree() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        // 勾选框
        GestureDetector(
          onTap: () {
            setState(() {
              _isAgree = !_isAgree;
            });
          },
          child:
              _isAgree
                  ? Image.asset('assets/isAgree_on.png', gaplessPlayback: true)
                  :
                  // 勾选框
                  Image.asset('assets/isAgree.png', gaplessPlayback: true),
        ),

        Padding(
          padding: EdgeInsets.only(left: 6.0),
          child: RichText(
            text: TextSpan(
              style: TextStyle(color: Color(0xFF7F7F7F), fontSize: 14.0),
              text: '我已同意',
              children: [
                TextSpan(
                  text: '《隐私条款》',
                  style: TextStyle(color: Color(0xFF00BE9A)),
                ),
                TextSpan(text: '和'),
                TextSpan(
                  text: '《服务条款》',
                  style: TextStyle(color: Color(0xFF00BE9A)),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  /// 登录按钮 + 验证码登录 + 需要帮助
  Widget _buildLoginButton() {
    return Column(
      children: [
        GestureDetector(
          onTap: () {
            _loginButtonOnTap();
          },
          child: Container(
            height: 44.0,
            alignment: Alignment.center,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(4.0),
              gradient: LinearGradient(
                // 渐变色
                colors: [Color(0xFF3CCEAF), Color(0xFF27BA9B)],
              ),
            ),
            child: Text(
              '登录',
              style: TextStyle(color: Colors.white, fontSize: 14.0),
            ),
          ),
        ),

        // 验证码登录和需要帮助
        Padding(
          padding: EdgeInsets.only(top: 10.0),
          child: Container(
            padding: EdgeInsets.only(left: 20.0, right: 20.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '验证码登录',
                  style: TextStyle(fontSize: 14.0, color: Color(0xff7F7F7F)),
                ),
                // 需要帮助
                Text(
                  '需要帮助',
                  style: TextStyle(fontSize: 14.0, color: Color(0xFF00BE9A)),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  /// 其他登录方式
  Widget _buildOtherLogin() {
    return Container(
      padding: EdgeInsets.only(left: 20.0, right: 20.0),
      child: Column(
        children: [
          Container(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(
                  width: 18.0,
                  height: 1.0,
                  decoration: BoxDecoration(color: Color(0xFFC4C4C4)),
                ),
                Padding(
                  padding: EdgeInsets.only(left: 10.0, right: 10.0),
                  child: Container(
                    child: Text(
                      '其他登录方式',
                      style: TextStyle(
                        color: Color(0xFF7F7F7F),
                        fontSize: 14.0,
                      ),
                    ),
                  ),
                ),
                Container(
                  width: 18.0,
                  height: 1.0,
                  decoration: BoxDecoration(color: Color(0xFFC4C4C4)),
                ),
              ],
            ),
          ),
          Padding(
            padding: EdgeInsets.only(top: 20.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Image.asset('assets/icon_login_wechat.png'),
                Padding(
                  padding: EdgeInsets.only(left: 32.0, right: 32.0),
                  child: Image.asset('assets/icon_login_qq.png'),
                ),
                Image.asset('assets/icon_login_weibo.png'),
              ],
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xFFF7F7F8),
      appBar: AppBar(
        backgroundColor: Color(0xFF00BF9B),
        shadowColor: Colors.transparent,
        // 阴影偏移
        elevation: 3,
        // 左侧布局
        leading: IconButton(
          // 苹果风格的返回按钮
          // icon: Icon(Icons.arrow_back_ios),
          icon: Image.asset("assets/fanhui_light.png"),
          onPressed: () {
            // 点击返回按钮, 关闭当前页面
            Navigator.pop(context);
          },
        ),
        // 右侧布局
        actions: [
          GestureDetector(
            onTap: () {
              // 点击注册按钮, 跳转到注册页面
              Navigator.push(
                context,
                CupertinoPageRoute(
                  builder: (BuildContext context) {
                    return RegisterMobilePage();
                  },
                ),
              );
            },
            child: Container(
              alignment: Alignment.center,
              margin: EdgeInsets.only(right: 10),
              child: Text(
                "新用户注册",
                style: TextStyle(
                  color: Color(0xFFF4F4F4),
                  fontSize: 16,
                  fontWeight: FontWeight.w400,
                ),
              ),
            ),
          ),
        ],
      ),
      // SingleChildScrollView 可以页面自适应滚动, 放不下的时候滚动
      body: GestureDetector(
        onTap: () {
          // 点击空白处, 隐藏键盘
          if (_accountFocusNode.hasFocus) {
            _accountFocusNode.unfocus();
          }
          if (_passwordFocusNode.hasFocus) {
            _passwordFocusNode.unfocus();
          }
        },
        child: SingleChildScrollView(
          child: Container(
            child: Column(
              children: [
                // 绿色背景 + 账号密码输入框 + 小兔子
                _buildLoginCard(),
                // 用户协议
                Padding(
                  padding: EdgeInsets.only(top: 26.0),
                  child: _buildAgree(),
                ),
                // 登录按钮 + 验证码登录 + 需要帮助
                Padding(
                  padding: EdgeInsets.only(top: 26.0, left: 20.0, right: 20.0),
                  child: _buildLoginButton(),
                ),
                // 其他登录方式
                Padding(
                  padding: EdgeInsets.only(top: 60.0),
                  child: _buildOtherLogin(),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
